/**
 * Created by DevilsEyes on 2016/3/14.
 */
//在这里进行全局的计时器的绑定与回调
'use strict';

define(function () {

    var count = 0;
    var callbackList = {};

    function Timer($dom, cb) {
        if (typeof cb != 'function')throw '需要回调';
        this.id = count;
        this.$dom = $dom;
        $dom.attr('timer-set', count);
        this.fire = cb;
        this.creatTime = new Date().getTime();
        return this;
    }

    var call = function () {
        var time = new Date().getTime();
        for (var id in callbackList) {
            if ($('[timer-set=' + id + ']').length > 0) {
                callbackList[id]
                    .fire(time);
            } else {
                delete callbackList[id];
            }
        }
    };

    setInterval(call, 1000);

    var mod = {
        register: function ($dom, cb) {
            count++;
            callbackList[count] = new Timer($dom, cb);
            return count;
        },
        logout: function (id) {
            delete callbackList[id];
        },
        queue: function (initFunc) {
            initFunc();
            return {
                promise: new Promise(function (resolve) {
                    resolve();
                }),
                go: function (func, time) {
                    this.promise
                        .then(function (resolve) {
                            setTimeout(function () {
                                resolve();
                            }, time || 0);
                        })
                        .done(func);

                    return this;
                }
            }

        }
    };

    return mod;
});